import { defineStore } from 'pinia'
import piniaPersistConfig from '../persist'

export interface CacheState {
  roleList: any[] | null
  roleListTimestamp: number
  cacheExpireTime: number // 缓存过期时间（毫秒）
}

export const useCacheStore = defineStore('cache', {
  state: (): CacheState => ({
    roleList: null,
    roleListTimestamp: 0,
    cacheExpireTime: 5 * 60 * 1000, // 5分钟缓存
  }),

  getters: {
    // 检查角色列表缓存是否有效
    isRoleListValid(): boolean {
      if (!this.roleList || this.roleList.length === 0) return false
      const now = Date.now()
      return (now - this.roleListTimestamp) < this.cacheExpireTime
    }
  },

  actions: {
    // 设置角色列表缓存
    setRoleList(roleList: any[]) {
      this.roleList = roleList
      this.roleListTimestamp = Date.now()
    },

    // 获取角色列表缓存
    getRoleList(): any[] | null {
      return this.isRoleListValid ? this.roleList : null
    },

    // 清除角色列表缓存
    clearRoleList() {
      this.roleList = null
      this.roleListTimestamp = 0
    },

    // 设置缓存过期时间
    setCacheExpireTime(expireTime: number) {
      this.cacheExpireTime = expireTime
    }
  },

  persist: piniaPersistConfig('cache')
})
